package sz.szsmk.citizencard.ui.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;
import com.google.zxing.WriterException;
import com.gyf.immersionbar.ImmersionBar;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.security.KeyStore;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.inject.Inject;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CakeBalanceBeanRes;
import sz.szsmk.citizencard.model.network.bean.response.CakeQRBeanRes;
import sz.szsmk.citizencard.model.network.bean.response.CheckVirCakeBeanRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.IPayCodeMvpView;
import sz.szsmk.citizencard.mvp.presenter.PayCodePresenter;
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean;
import sz.szsmk.citizencard.ui.dialogs.RealNameCheckDialog;
import sz.szsmk.citizencard.ui.dzsmkavtivity.AppBaseActivity;
import sz.szsmk.citizencard.ui.newversion.config.Constants;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.QrCodeUtils;
import sz.szsmk.citizencard.util.StringUtils;

/**
 * author : hyt
 * date : 2020/5/20
 * description : 支付码
 */
@Route("payCode")
public class PayCodeActivity extends AppBaseActivity implements IPayCodeMvpView {

    @Inject
    PayCodePresenter presenter;

    private Vibrator mVibrator;
    private CountDownTimer ermCountDownTimer;
    private CountDownTimer autoRefreshCountDownTimer;

    LinearLayout lin_refresh;
    ImageView qrCode;
    ImageView refresh_icon;
    TextView refresh_state;

    TextView tv_cakeMoney;
    TextView tv_cardNumber;

    boolean iseyeCheck = true;
    boolean iseyeMoneyCheck = true;

    @Override
    protected CharSequence getTopTitle() {
        return null;
    }


    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{ presenter };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent().inject(this);
        setContentView(R.layout.activity_paycode);


        lin_refresh = findViewById(R.id.lin_refresh);
        qrCode= findViewById(R.id.qr_code_img);
        refresh_icon= findViewById(R.id.refresh_icon);
        refresh_state= findViewById(R.id.refresh_state);

        tv_cakeMoney= findViewById(R.id.tv_cakeMoney);
        tv_cardNumber= findViewById(R.id.tv_cardNumber);


        lin_refresh.setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_transactions).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_recharge).setOnClickListener(this::onViewClicked);
        findViewById(R.id.dzsmk_code).setOnClickListener(this::onViewClicked);

        findViewById(R.id.tv_identityCode).setOnClickListener(this::onViewClicked);

        findViewById(R.id.iv_qr_right).setOnClickListener(this::onViewClicked);
        findViewById(R.id.iv_eyeState).setOnClickListener(this::onViewClicked);
        findViewById(R.id.iv_eyeMoney).setOnClickListener(this::onViewClicked);


//        showLoadingDialog();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        init();
    }

    @Override
    protected void initSystemBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0.2f)
                .statusBarColor(R.color.color_FF7466).init();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    String cakeCode = "";

    private void init() {
        cakeCode = getIntent().getExtras().getString("cakeCode");
        //查询余额
        presenter.queryCakeBalance(cakeCode);
        presenter.getPayCode(cakeCode);
        //查询卡号
        presenter.getIsOpenPayCode();

        tv_cardNumber.setText("卡号："+cakeCode);

        mVibrator = (Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE);
        if (ermCountDownTimer == null) {
            ermCountDownTimer = new CountDownTimer(3 * 1000, 1000) {
                @Override
                public void onTick(long l) {

                }

                @Override
                public void onFinish() {
                    lin_refresh.setEnabled(true);
                    qrCode.setEnabled(true);
                    refresh_icon.setImageResource(R.mipmap.icon_refresh);
                    refresh_state.setText("请点击二维码刷新");
                    autoRefreshCountDownTimer.start();
                }
            };
        }
        if (autoRefreshCountDownTimer == null) {
            autoRefreshCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
                @Override
                public void onTick(long l) {

                }

                @Override
                public void onFinish() {
                    lin_refresh.setEnabled(false);
                    qrCode.setEnabled(false);
                    refresh_icon.setImageResource(R.drawable.adress_check);
                    refresh_state.setText("已刷新");

                    if (ermCountDownTimer != null) {
                        ermCountDownTimer.start();
                        mVibrator.vibrate(1000);
                    }
                }
            };
        }
    }


    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        int id = view.getId();
        if (id == R.id.lin_refresh) {
            presenter.getPayCode(cakeCode);
            if (ermCountDownTimer != null) {
                ermCountDownTimer.start();
            }

            lin_refresh.setEnabled(false);
            qrCode.setEnabled(false);
            autoRefreshCountDownTimer.cancel();
        } else if (id == R.id.tv_transactions) {//交易记录
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/mdlPages/transactions?cardNo=" + cakeCode);
            JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
        } else if (id == R.id.tv_recharge) {//充值
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/mdlPages/recharge?access_token=" +
                    ACache.get(DaggerApplication.getIns()).getAsString("access_token"));
            JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
        } else if (id == R.id.dzsmk_code) {//乘车码
            EventBus.getDefault().post(new MessageEvent(MessageEvent.TO_DZSMK));
        } else if (id == R.id.tv_identityCode) {
            goIdentityCodeActivity();
        } else if (id == R.id.iv_qr_right) {//账户安全
            JumpUtils.jumptoNatvie(this, Constants.ACCOUNTSECURITYACTIVITY, 0, null);
        } else if (id == R.id.iv_eyeState) {
            if (iseyeCheck) {
                tv_cardNumber.setText("卡号：*************");
            } else {
                tv_cardNumber.setText("卡号：" + cakeCode);
            }
            iseyeCheck = !iseyeCheck;
        } else if (id == R.id.iv_eyeMoney) {
            if (iseyeMoneyCheck) {
                tv_cakeMoney.setText("余额：**元");
            } else {
                if (bignum4 != null) {
                    tv_cakeMoney.setText("余额：" + bignum4.toString() + "元");
                }
            }
            iseyeMoneyCheck = !iseyeMoneyCheck;
        }
    }



    RealNameCheckDialog realNameCheckDialog;
    private void goIdentityCodeActivity() {
        AppHomeCardBean appHomeCardBean = DaggerApplication.getAppHomeCardBean();
        if ("L2".equals(appHomeCardBean.getLevel()) || "L3".equals(appHomeCardBean.getLevel())) {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.ID_CARD, appHomeCardBean.getIdCard());
            bundle.putString(Constant.ID_NAME, appHomeCardBean.getCustName());
            JumpUtils.gotoNeedGesture(mContext, "identityCodeActivity", bundle);
        }else{
            realNameCheckDialog = new RealNameCheckDialog(this);
            realNameCheckDialog.show();
        }
    }

    @Override
    public void onPayCodeSuccess(CakeQRBeanRes response) {
        //支付码 返回
        if (!StringUtils.isBlank(response.getMarkCode())) {
            try {
                response.getMarkCode();
                Bitmap qrCodeImg = QrCodeUtils.createQRCode(response.getMarkCode(), this.qrCode.getWidth());
                qrCode.setImageBitmap(qrCodeImg);
                refresh_icon.setImageResource(R.drawable.adress_check);
                refresh_state.setText("已刷新");
                if(ermCountDownTimer!=null){
                    ermCountDownTimer.start();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    BigDecimal bignum4;

    @Override
    public void queryCakeBalanceSuccess(CakeBalanceBeanRes bean) {
        //获取余额
        BigDecimal bignum1 = new BigDecimal(bean.getCakeBalance());
        BigDecimal bignum3 = bignum1.divide(new BigDecimal(100));
        bignum4 = bignum3.setScale(2);
        tv_cakeMoney.setText("余额："+bignum4.toString()+"元");
    }

    @Override
    public void onIsOpenPayCodeSuccess(CheckVirCakeBeanRes bean) {
        tv_cardNumber.setText("卡号："+ bean.getCardNo());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ermCountDownTimer != null) {
            ermCountDownTimer.cancel();
            ermCountDownTimer = null;
        }
        if (autoRefreshCountDownTimer != null) {
            autoRefreshCountDownTimer.cancel();
            autoRefreshCountDownTimer = null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (ermCountDownTimer != null) {
            ermCountDownTimer.cancel();
        }
        if (autoRefreshCountDownTimer != null) {
            autoRefreshCountDownTimer.cancel();
        }
    }

    @Override
    public void fail(BaseBean bean) {
        Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
